package com.aliya.glide.module

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.Log
import com.aliya.glide.builder.InternalCacheDiskCacheCopyFactory
import com.aliya.glide.builder.LruResourceCacheAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.Glide.RequestOptionsFactory
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.Engine
import com.bumptech.glide.load.engine.bitmap_recycle.*
import com.bumptech.glide.load.engine.cache.*
import com.bumptech.glide.load.engine.executor.GlideExecutor
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.manager.ConnectivityMonitorFactory
import com.bumptech.glide.manager.RequestManagerRetriever.RequestManagerFactory
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.setEngine

/**
 * 第一次调用 Glide#get() 时, 创建 GlideModule
 * 通过反射创建 GeneratedAppGlideModuleImpl 来配置自定义的 GlideModule
 *
 * @author a_liYa
 * @date 2021/11/1 22:15.
 *
 */
@GlideModule
class SingleGlideModule : AppGlideModule() {


    override fun applyOptions(context: Context, builder: GlideBuilder) {
        var bitmapPool: BitmapPool
        var arrayPool: ArrayPool
        var memoryCache: MemoryCache
        var diskCacheFactory: DiskCache.Factory
        /** 通过 GlideBuilder 修改 Glide 默认配置 */
        MemorySizeCalculator.Builder(context).build().run {
            builder.setMemorySizeCalculator(this)

            // bitmapPoolSize 计算规则：1个屏幕大小的ARGB_8888配置Bitmap getByteCount返回的大小
            bitmapPool = if (bitmapPoolSize > 0) {
                LruBitmapPool(bitmapPoolSize.toLong())
            } else {
                BitmapPoolAdapter() // 没有存储能力
            }

            // 缓存池（默认4MB），作用解码及解析文件时提供缓冲区（byte[]）的复用逻辑，预防内存抖动
            arrayPool = LruArrayPool(arrayPoolSizeInBytes)

            // memoryCacheSize 计算规则：2个屏幕大小的ARGB_8888配置Bitmap getByteCount返回的大小
            memoryCache = LruResourceCacheAdapter(memoryCacheSize.toLong())
        }
        builder.setBitmapPool(bitmapPool)
        builder.setArrayPool(arrayPool)
        builder.setMemoryCache(memoryCache)

        // 250MB, /data/user/0/包名/cache/image_manager_disk_cache
        diskCacheFactory = GlideHelper.diskCacheFactory
        builder.setDiskCache(diskCacheFactory)
        // 开启默认关闭的 crossFade 功能
        builder.setDefaultTransitionOptions(Drawable::class.java, DrawableTransitionOptions.withCrossFade())

    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {

    }
}